package org.dromara.common.core.exception;

import cn.hutool.core.util.StrUtil;
import lombok.*;
import org.dromara.common.core.domain.ErrorCode;

import java.io.Serial;
import java.util.Locale;

/**
 * 业务异常
 *
 * @author ruoyi
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
public final class ServiceException extends RuntimeException {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 错误提示
     */
    private String message;

    /**
     * 错误明细，内部调试错误
     */
    private String detailMessage;

    public ServiceException(ErrorCode errorCode, Object... params) {
        // 参数校验：确保 errorCode 不为 null
        if (errorCode == null) {
            throw new IllegalArgumentException("ErrorCode cannot be null");
        }

        // 支持错误消息国际化（示例代码，实际应用中需要替换为具体的国际化实现）
        String msgTemplate = errorCode.getMsg();
        // 高性能：缓存未格式化的错误消息（示例，需根据实际情况调整）
        if (params == null || params.length == 0) {
            this.message = msgTemplate;
        } else {
            // 安全地格式化错误消息
            this.message = StrUtil.format(msgTemplate, params);
        }

        this.code = errorCode.getCode();
    }

    public ServiceException(String message) {
        this.message = message;
    }

    public ServiceException(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public ServiceException setMessage(String message) {
        this.message = message;
        return this;
    }

    public ServiceException setDetailMessage(String detailMessage) {
        this.detailMessage = detailMessage;
        return this;
    }
}
